var ProxyPool = require("./ProxyPool.js");
var ProxyInfo = require("../common/ProxyInfo.js");
var Util = require("../util/util.js");
var request = require("request");
var App = require("../common/App.js");
var fs2 = require('fs');

module.exports = new SyncProxy();

function SyncProxy(){
    //单例模式
    if(typeof arguments.callee.instance === "object"){
        return arguments.callee.instance;
    }
    arguments.callee.instance = this;
}

SyncProxy.prototype.start = function(){
    var that = this;
    var apiUrl = App.config.SyncProxyUrl;
    request.get(apiUrl,function(err, res, body){
        if(!err && res.statusCode==200){
            try{
                var iplist = JSON.parse(body);
                iplist = that.sort(iplist);
                var len = iplist.length;
                for(var i=0;i<len;i++){
                    var p = iplist[i];
                    var proxy = new ProxyInfo(p);
                    ProxyPool.push(proxy);
                }
            }catch(err) {
                console.log("代理池添加出错请查看",err)
            }
        }else{
            console.log("SyncProxy fail "+err);
        }
    });
}

/**
 * 排序，按照端口优先级排序
 * @param iplist
 */
SyncProxy.prototype.sort = function(iplist){
    var stablePort = App.config.stablePort;
    var newIplist = [];
    var stableList = {};
    var unstableList = [];
    var len = iplist.length;

    //最近验证过有效的代理
    for(var i=0;i<len;i++){
        var p = iplist[i];
        if(p.resBaiduTime>0){
            var proxy = new ProxyInfo();
            proxy.host = p.host;
            proxy.port = p.port;
            newIplist.push(proxy);
        }
    }

    //相对稳定的端口
    for(var i=0;i<len;i++){
        var port = parseInt(iplist[i].port);
        if(stablePort.indexOf(port)>=0){
            if(stableList[port]==undefined){
                stableList[port] = [];
            }
            stableList[port].push(iplist[i]);
        }else{
            unstableList.push(iplist[i]);
        }
    }

    var slen = stablePort.length;
    for(var i=0;i<slen;i++){
        var port = stablePort[i];
        if(stableList[port] instanceof Array){
            newIplist = newIplist.concat(stableList[port]);
        }
    }

    //在累加不稳定的代理
    newIplist = newIplist.concat(unstableList);
    //console.log(newIplist);
    //fs2.writeFileSync('proxy.json',JSON.stringify(newIplist));
    return newIplist;
}
